import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import { queryLoginUser } from '@/api/user'

const initialState = {
  user: {}
}

export const loadUserInfo = createAsyncThunk('userReducer/loadUserInfo', async () => {
  const res = await queryLoginUser()
  return res?.data || {}
})

export const userSlice = createSlice({
  name: 'userReducer',
  initialState,
  reducers: {
    setUserAction (state, { payload }) {
      state.user = payload
    },
    clearUserAction (state) {
      state.user = {}
    }
  },
  extraReducers: builder => {
    builder.addCase(loadUserInfo.fulfilled, (state, { payload }) => {
      state.user = payload
    })
  }
})

export const { setUserAction, clearUserAction } = userSlice.actions

export default userSlice.reducer
